#include "mysql.h"
// 初始化目录栈
int init_list(Link_list_t *file_stack) {
    file_stack->head = NULL;
    file_stack->tail = NULL;
    file_stack->length = 0;
    return 0;
}

// 入栈（添加目录节点）
int add_catalog(Link_list_t *catalog, int id) {
    //先申请一块内存 用来存放节点
    Node_t *newNode = (Node_t*)calloc(1, sizeof(Node_t));
    newNode->id = id;
    if (catalog->length == 0) {//如果此时栈里面无节点
        catalog->head = newNode;
        catalog->tail = newNode;
    } else {
        catalog->tail->next_node = newNode;
        catalog->tail = newNode;
    }
    catalog->length++;
    return 0;
}

// 出栈（删除当前目录）
int delete_catalog(Link_list_t *catalog) {
    if (catalog->length == 0) {//栈中无数据
        return -1;
    }

    if (catalog->length == 1) {//栈里面只有一个节点
        free(catalog->head);//先释放节点内存
        catalog->head = NULL;
        catalog->tail = NULL;
    } else {
        Node_t *temp = catalog->head;
        while (temp->next_node != catalog->tail) {//找到尾结点的前一个节点
            temp = temp->next_node;
        }
        
        free(catalog->tail);
        catalog->tail = temp;//更新尾结点
        catalog->tail->next_node = NULL;
    }
    catalog->length--;
    return 0;
}

// 打印链表（并拼接路径(id)字符串） eg:1/2/3    
int printf_Linklist(Link_list_t *catalog, char* idPath) {//idPath用来给调用函数返回拼接好的路径
    if (catalog->head == NULL) {
        printf("Linklist is NULL\n");
        return 0;
    }

    Node_t *temp = catalog->head;

    while (temp->next_node) {//从头结点(栈底)到尾结点(栈顶) 依次拼接
//        printf("%d/", temp->id);
        char idChar[50];
        sprintf(idChar, "%d", temp->id);
        strcat(idPath, idChar);
        strcat(idPath, "/");
        temp = temp->next_node;
    }
    //拼接最后一个节点的id
    char idChar[12];
    sprintf(idChar, "%d", temp->id);
    strcat(idPath, idChar);

    return 0;
}
